/*
 * @Author: your name
 * @Date: 2021-06-02 10:34:56
 * @LastEditTime: 2021-06-02 17:11:18
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \bazai_island_api\middlewares\auth.js
 */
const basicAuth = require('basic-auth')
const jwt = require('jsonwebtoken')

class Auth {
    constructor(level) {
        this.level = level || 1
        Auth.USER = 8
        Auth.ADMIN = 16
        Auth.SUPER_ADMIN = 32
    }

    get m () {
        return async (ctx, next) => {
            const userToken = await basicAuth(ctx.req)
            let errMsg = 'token不合法'
            let decode = ''
            if (!userToken || !userToken.name) {
                throw new global.errs.Forbbiden(errMsg)
            }
            try {
                decode = jwt.verify(userToken.name, global.config.security.secretKey)
            } catch(error) {
                // token不合法
                // token过期
                if (error.name === 'TokenExpiredError') {
                    errMsg = 'token已过期'
                }
                throw new global.errs.Forbbiden(errMsg)
            }

            if (decode.scope < this.level) {
                errMsg = '权限不足'
                throw new global.errs.Forbbiden(errMsg)
            }

            // uid, scope
            ctx.auth = {
                uid: decode.uid,
                scope: decode.scope
            }

            await next()

            // Koa Node.js
            // token 检测
            // token 开发者 传递令牌
            // token body header 约定
            // HTTP 规定 身份验证机制 HttpBasicAuth
        }
    }

    static verifyToken(token) {
        try {
            jwt.verify(token,
                global.config.security.secretKey)
            return true
        }
        catch (error) {
            return false
        }
    }
}

module.exports = {
    Auth
}
